#!/bin/bash

DAEMON=/usr/sbin/osspd
PIDFILE=/var/run/osspd.pid
NAME=osspd

start() {
    echo "Starting $NAME..."
    if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
        echo "$NAME is already running."
        return 1
    fi

    modprobe cuse
    start-stop-daemon --start --quiet --background \
        --pidfile "$PIDFILE" --make-pidfile \
        --exec "$DAEMON"
    echo "$NAME started."
}

stop() {
    echo "Stopping $NAME..."
    start-stop-daemon --stop --quiet --pidfile "$PIDFILE"
    rm -f "$PIDFILE"
    echo "$NAME stopped."
}

status() {
    if [ -f "$PIDFILE" ]; then
        PID=$(cat "$PIDFILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            # Make sure it's really osspd
            if pgrep -x "$NAME" | grep -qx "$PID"; then
                echo "$NAME is running with PID $PID."
                return 0
            else
                # PID file is outdated
                echo "$NAME PID file is outdated. Fixing..."
            fi
        else
            echo "$NAME PID file is stale. Fixing..."
        fi
    fi

    # Try to find running process and update PID file
    NEWPID=$(pgrep -x "$NAME")
    if [ -n "$NEWPID" ]; then
        echo "$NEWPID" > "$PIDFILE"
        echo "$NAME is running with PID $NEWPID (updated PID file)."
        return 0
    else
        echo "$NAME is not running."
        return 1
    fi
}

case "$1" in
    start)   start ;;
    stop)    stop ;;
    restart) stop; start ;;
    status)  status ;;
    *)       echo "Usage: $0 {start|stop|restart|status}"; exit 1 ;;
esac

exit 0
